/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  TextInput,
  Dimensions,
  TouchableOpacity,
  Image,
  Alert
} from 'react-native';

import Toast from 'react-native-easy-toast' 
import styles1 from './styles/Pager.style';
import {colors} from './styles/Pager.style';

import {KeyboardAwareScrollView} from 'react-native-keyboard-aware-scrollview';
import { Hoshi,Kohana,Makiko,Hideo,Akira,Fumi} from 'react-native-textinput-effects';

var _navigator;

var net = require("./net/NetUitl");
var timer = 60;
var authtimer;
var Header = require("./Component/Header");

class FixPassword extends Component {
	constructor(props) {  
		super(props);
		_navigator = this.props.navigator;
		this.state={
			username:"",
			password:"",
			code:"",
			auth:"获取验证码",
			authStatus:false,
		}
		
		this._FixPassword = this._FixPassword.bind(this);
		this.getAuth = this.getAuth.bind(this);
		this._FixCallBack = this._FixCallBack.bind(this);
  	}
	
	_netCallBack(data){
		
	}
	
	_errorCallBack(){
		
	}
	
	_FixCallBack(data){
		console.log(data);
		if(data.code === "1"){
			this.dropdown.alertWithType('info', '提醒','密码修改成功');
			setTimeout(()=>{_navigator.pop()},1500);
		}else if(data.code === "0"){
			this.dropdown.alertWithType('warn', '提醒','验证码已失效');
		}
	}
	
	_FixPassword(){
		var flag = this.check();
		if(!flag)
			return;
		if(this.state.code == "")
		{
			this.dropdown.alertWithType('warn', '提醒',"验证码不能为空");
			return;
		}
		
		let formData = new FormData();  
		formData.append("phonenumber",this.state.username);  
		formData.append("password",this.state.password);  
		formData.append("phonecode",this.state.code);  
		var fetchOptions = {
          	method: 'POST',
          	headers: {     
          		'Accept': 'application/json',
          	},
          	body: formData
       	};
       	
		net.postFrom("http://www.idolly.com/user/index/forgetpassword"
				,fetchOptions
				,this._FixCallBack
				,this._errorCallBack);
				
//		net.postJson("http://www.idolly.com/user/index/forgetpassword"
//				,this.toQueryString({"phonenumber":this.state.username,"password":this.state.password,"phonecode":this.state.code})
//				,this._FixCallBack
//				,this._errorCallBack);
	}
	
	componentWillUnmount(){
		clearInterval(authtimer);
	}
	
	check(){
		if(this.state.username === ""){
			this.dropdown.alertWithType('warn', '提醒',"手机号为空");
			return false;
		}
		if(this.state.password === ""){
			this.dropdown.alertWithType('warn', '提醒',"密码为空");
			return false;
		}
		
		return true;
	}
	
	toQueryString(obj) {
		return obj ? Object.keys(obj).sort().map(function (key) {
		    var val = obj[key];
		    if (Array.isArray(val)) {
		        return val.sort().map(function (val2) {
		            return encodeURIComponent(key) + '=' + encodeURIComponent(val2);
		        }).join('&');
		    }
		    return encodeURIComponent(key) + '=' + encodeURIComponent(val);
		}).join('&') : '';
	}
		
	getAuth(){
		var flag = this.check();
		if(!flag)
			return;
		timer = 60;
		this.setState({authStatus:true});
		
		let formData = new FormData();  
		formData.append("phonenumber",this.state.username);  
		var fetchOptions = {
          	method: 'POST',
          	headers: {     
          		'Accept': 'application/json',       		
          	},
          	body: formData
       	};
//	
		net.postFrom("http://www.idolly.com/message/index/getphonecode"
				,fetchOptions
				,this._netCallBack 
				,this._errorCallBack);
//		net.postJson("http://www.idolly.com/message/index/getphonecode"
//				,{"phonenumber":this.state.username}
//				,this._netCallBack
//				,this._errorCallBack);
				
		authtimer = setInterval(() => {
			timer--;
			this.setState({auth:"等待"+timer+"s后获取"});
			if(timer == 0){
				clearInterval(authtimer);
				this.setState({auth:"重新获取验证码"});
				this.setState({authStatus:false});
			}
		},1000);
	}
	
	render() {
	    return ( 
	      	<View style={styles1.container}>
	      		<Header name="修改密码" IconLeft="chevron-left" onPressLeft={()=>_navigator.pop()}/>
	      		<KeyboardAwareScrollView style={{flex:1}} getTextInputRefs={() => { return [this._textInputRef];}}>
	      		<View style={[styles1.container,{justifyContent: 'center'}]}>
		      		<View>
		      			<Image source={require('./image/common/logo.png')} style={{width:Dimensions.get('window').width,height:200}}/>
		      		</View>
		      		<View style={{width:Dimensions.get('window').width-40,margin:0}}>
			      		<Hoshi
						    label={"请输入手机号"}
						    borderColor={colors.basecolor}
						    onChangeText={(text) => this.setState({username:text})}
        					value={this.state.username}
						/>
						<Hoshi
						    label={"密码"}
						    borderColor={colors.basecolor}
			      			secureTextEntry={true}
						    onChangeText={(text) => this.setState({password:text})}
        					value={this.state.password}
						/>
	                  	<View style={{flexDirection:'row'}}>
		                  	<Hoshi
		                  		style={{flex:1}}
							    label={"验证码"}
							    borderColor={colors.basecolor}
				      			secureTextEntry={true}
							    onChangeText={(text) => this.setState({code:text})}
	        					value={this.state.code}
							/>
		                  	<TouchableOpacity disabled={this.state.authStatus} onPress={this.getAuth}>
				      			<View style={styles.registerBtn}>
				      				<Text>{this.state.auth}</Text>
				      			</View>
			      			</TouchableOpacity>
	                  	</View>
			      		<TouchableOpacity onPress={this._FixPassword}>
			      			<View style={styles.login}>
			      				<Text>重新设置密码</Text>
			      			</View>
			      		</TouchableOpacity>
			      		<View style={{flexDirection:'row'}}>
			      			<View style={{flex:1}}></View>
			      		</View>
		      		</View>
	      		</View>
	      		<Toast ref="toast"/>
	      		</KeyboardAwareScrollView>
	      	</View>
	    );
	}
}

const styles = StyleSheet.create({
	container: {
	    flex: 1,
	    alignItems: 'center',
	    backgroundColor: '#FAF4FF',
	},
	login:{
		width:Dimensions.get('window').width-40,
		height:40,
		marginTop:50,
		margin:0,
	    justifyContent: 'center',
	    alignItems: 'center',
	    borderWidth:1,
	    borderColor:"#555555",
	    borderRadius:20,
	    backgroundColor:'white'
	},
	registerBtn:{
		paddingLeft:10,
		paddingRight:10,
		height:40,
		justifyContent: 'center',
	    alignItems: 'center',
		borderWidth:1,
	    borderColor:"#555555",
	    borderRadius:20,
	    backgroundColor:'white',
	    marginTop:10
	}
});

module.exports = FixPassword;
